package com.example.mental.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mental.entity.Article;
import com.example.mental.entity.User;
import com.example.mental.service.ArticleService;
import com.example.mental.vo.ArticleVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl extends ServiceImpl<Article> implements ArticleService {

    @Autowired
    private UserService userService;

    @Override
    public List<ArticleVO> getLatestArticles(int limit) {
        // 获取最新的文章列表
        List<Article> articles = list(new LambdaQueryWrapper<Article>()
                .eq(Article::getStatus, 1)
                .orderByDesc(Article::getCreatedAt)
                .last("LIMIT " + limit));
        
        if (articles.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 获取作者信息
        List<Long> userIds = articles.stream()
                .map(Article::getUserId)
                .distinct()
                .collect(Collectors.toList());
        
        Map<Long, User> userMap = userService.listByIds(userIds).stream()
                .collect(Collectors.toMap(User::getId, user -> user));
        
        // 转换为VO
        return articles.stream().map(article -> {
            ArticleVO vo = new ArticleVO();
            BeanUtils.copyProperties(article, vo);
            
            User author = userMap.get(article.getUserId());
            if (author != null) {
                vo.setAuthorName(author.getName());
                vo.setAuthorAvatar(author.getAvatar());
            }
            
            return vo;
        }).collect(Collectors.toList());
    }
} 